﻿using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;

namespace DxfMonitor.Data
{
    public class DxfHistoryStatus : IEquatable<DxfHistoryStatus>
    {
        private string dirFull;
        public DxfHistoryStatus(DxfFile dxfFile)
        {
            this.dirFull = dxfFile.Folder.FolderFull;
            FullPath = Path.Combine(dirFull, dxfFile.RelativePath);
            RelativePath = dxfFile.RelativePath;
            ModifiedDate = dxfFile.ModifiedDate;
        }

        public DxfHistoryStatus(string dirFull, string fileFull)
        {
            this.dirFull = dirFull;
            FullPath = fileFull;
            RelativePath = fileFull.Replace(dirFull, "");
            ModifiedDate = new FileInfo(fileFull).LastWriteTime;
        }
        public string FullPath { get; private set; }
        public string RelativePath { get; set; }
        public DateTime ModifiedDate { get; set; }

        private RelayCommand openFolderCommand;
        public RelayCommand OpenFolderCommand => openFolderCommand ?? (openFolderCommand = new RelayCommand(ExecuteOpenFolderCommand, CanExecuteOpenFolderCommand));

        private bool CanExecuteOpenFolderCommand()
        {
            return Directory.Exists(dirFull);
        }



        private bool isOpenFolderning;
        private void ExecuteOpenFolderCommand()
        {
            isOpenFolderning = true;
            OpenFolderCommand.NotifyCanExecuteChanged();
            try
            {
                var p = new Process();
                p.StartInfo = new ProcessStartInfo("explorer.exe")
                {
                    UseShellExecute = true,
                    Arguments = "/select, " + FullPath

                };

                p.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            OpenFolderCommand.NotifyCanExecuteChanged();
            isOpenFolderning = false;
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as DxfHistoryStatus);
        }

        public static readonly Regex OkRegex = new Regex(@"\s*ok", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        public static string GetPathWithOutOk(string s)
        {
            return OkRegex.Replace(s, "");
        }
        public bool Equals(DxfHistoryStatus other)
        {
            if (other == null) return false;
            return GetPathWithOutOk(RelativePath) == GetPathWithOutOk(other.RelativePath) && ModifiedDate == other.ModifiedDate;
        }
        public override int GetHashCode()
        {
            return HashCode.Combine(GetPathWithOutOk(RelativePath), ModifiedDate);
        }
    }
}
